/**
 * @description RunningHub API服务封装
 */
import { runningHub } from '../config/api';

/**
 * RunningHub 服务类
 * 用于与 RunningHub 服务进行交互
 */
class RunningHubService {
  constructor() {
    // 从配置文件中读取API Key和基础URL
    this.apiKey = runningHub.apiKey;
    this.baseUrl = runningHub.baseUrl;
  }

  /**
   * 设置 API Key（可用于运行时修改API Key）
   * @param {String} apiKey 
   */
  setApiKey(apiKey) {
    this.apiKey = apiKey;
  }

  /**
   * 获取当前使用的 API Key
   * @returns {String} 当前API Key
   */
  getApiKey() {
    return this.apiKey;
  }

  /**
   * 上传图片到 RunningHub
   * @param {String} filePath 本地文件路径
   * @returns {Promise<String>} 上传后的图片 URL
   */
  uploadImage(filePath) {
    return new Promise((resolve, reject) => {
      if (!this.apiKey) {
        reject(new Error('请先设置 API KEY'));
        return;
      }

      // 上传文件需要使用 formData
      let formData = {
        apiKey: this.apiKey,
        fileType:"image"
      };

      uni.uploadFile({
        url: `${this.baseUrl}/task/openapi/upload`,
        filePath: filePath,
        header: {

          "Host": "www.runninghub.cn"
        },
        name: 'file',
        formData: formData,
        success: (uploadRes) => {
          try {
            const data = JSON.parse(uploadRes.data);
            if (data.code === 0) {
              resolve(data.data); // 返回上传后的图片URL
            } else {
              reject(new Error(data.message || '上传失败'));
            }
          } catch (e) {
            reject(e);
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 创建 ComfyUI 任务
   * @param {String} workflowId 工作流 ID
   * @param {Array} nodeInfoList 节点信息列表
   * @returns {Promise<Object>} 任务创建结果
   */
  createComfyUITask(workflowId, nodeInfoList,workflow) {
    return new Promise((resolve, reject) => {
      if (!this.apiKey) {
        reject(new Error('请先设置 API KEY'));
        return;
      }

      uni.request({
        url: `${this.baseUrl}/task/openapi/create`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          "Host": "www.runninghub.cn"
        },
        data: {
          apiKey: this.apiKey,
          workflowId: workflowId,
          nodeInfoList: nodeInfoList,
          workflow:workflow
        },
        success: (res) => {
          if (res.data.code === 0) {
            resolve(res.data);
          } else {
            reject(new Error(res.data.message || '任务创建失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 查询任务状态
   * @param {String} taskId 任务 ID
   * @returns {Promise<Object>} 任务状态
   */
  queryTaskStatus(taskId) {
    return new Promise((resolve, reject) => {
      if (!this.apiKey) {
        reject(new Error('请先设置 API KEY'));
        return;
      }

      uni.request({
        url: `${this.baseUrl}/task/openapi/status`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          "Host": "www.runninghub.cn"
        },
        data: {
          apiKey: this.apiKey,
          taskId: taskId
        },
        success: (res) => {
          if (res.data.code === 0) {
            resolve(res.data);
          } else {
            reject(new Error(res.data.message || '查询任务状态失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 获取任务结果
   * @param {String} taskId 任务 ID
   * @returns {Promise<Object>} 任务结果
   */
  getTaskResult(taskId) {
    return new Promise((resolve, reject) => {
      if (!this.apiKey) {
        reject(new Error('请先设置 API KEY'));
        return;
      }

      uni.request({
        url: `${this.baseUrl}/task/openapi/outputs`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          "Host": "www.runninghub.cn"
        },
        data: {
          apiKey: this.apiKey,
          taskId: taskId
        },
        success: (res) => {
          if (res.data.code === 0) {
            resolve(res.data);
          } else {
            reject(new Error(res.data.message || '获取任务结果失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 取消任务
   * @param {String} taskId 任务 ID
   * @returns {Promise<Object>} 取消结果
   */
  cancelTask(taskId) {
    return new Promise((resolve, reject) => {
      if (!this.apiKey) {
        reject(new Error('请先设置 API KEY'));
        return;
      }

      uni.request({
        url: `${this.baseUrl}/task/openapi/v1/cancel`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          "Host": "www.runninghub.cn"
        },
        data: {
          apiKey: this.apiKey,
          taskid: taskId
        },
        success: (res) => {
          if (res.data.code === 0) {
            resolve(res.data);
          } else {
            reject(new Error(res.data.message || '取消任务失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 获取工作流信息，可用于查询节点 ID
   * @param {String} workflowId 工作流 ID
   * @returns {Promise<Object>} 工作流信息
   */
  getWorkflowJson(workflowId) {
    return new Promise((resolve, reject) => {
      if (!this.apiKey) {
        reject(new Error('请先设置 API KEY'));
        return;
      }

      uni.request({
        url: `${this.baseUrl}/api/openapi/getJsonApiFormat`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          "Host": "www.runninghub.cn"
        },
        data: {
          apiKey: this.apiKey,
          workflowId: workflowId
        },
        success: (res) => {
          if (res.data.code === 0) {
            resolve(res.data);
          } else {
            reject(new Error(res.data.message || '获取工作流信息失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }
}

// 导出服务实例
export const runningHubService = new RunningHubService();
export default runningHubService; 